package org.jeecg.modules.meter.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.entity.basedata.BaseCustomer;
import org.jeecg.entity.basedata.BaseProject;
import org.jeecg.entity.basedata.BaseTenant;
import org.jeecg.entity.charge.ChargeBills;
import org.jeecg.entity.charge.ChargeFeeRule;
import org.jeecg.entity.charge.ChargeFeeitem;

import org.jeecg.entity.meter.MeterHandRead;
import org.jeecg.common.util.DateUtil;
import org.jeecg.modules.meter.entity.MeterHadnExVo;
import org.jeecg.modules.meter.service.IMeterHandReadService;
import org.jeecg.modules.meter.service.IMeterService;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.vo.basedata.BaseRoomMeterVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 手抄表
 * @Author: jeecg-boot
 * @Date:   2021-01-17
 * @Version: V1.0
 */
@Slf4j
@Api(tags="手抄表")
@RestController
@RequestMapping("b/meter/hand")
public class MeterHandReadController {
	@Autowired
	private IMeterHandReadService meterHandReadService;
	@Autowired
    private IMeterService meterService;
	@Autowired
    private IFeignChargeService feignChargeService;


	/**
	  * 分页列表查询
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "手抄表-分页列表查询")
	@ApiOperation(value="手抄表-分页列表查询", notes="手抄表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<MeterHandRead >> queryPageList(BaseRoomMeterVo baseRoomMeterVo,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		Result<IPage<MeterHandRead>> result = new Result<IPage<MeterHandRead>>();
		Page<MeterHandRead> page = new Page<MeterHandRead>(pageNo, pageSize);
		List<MeterHandRead> pageList = meterHandReadService.findPage(page, baseRoomMeterVo);
        page.setRecords(pageList);
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}
	/**
	   房间所有收费项抄度数查询
	 */
	@AutoLog(value = "手抄表-分页列表查询")
	@ApiOperation(value="手抄表-分页列表查询", notes="手抄表-分页列表查询")
	@GetMapping(value = "/queryAllRoomHandList")
	public Result<IPage<MeterHandRead >> queryAllRoomHandList(@RequestParam("roomId") String roomId,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		Result<IPage<MeterHandRead>> result = new Result<IPage<MeterHandRead>>();
		Page<MeterHandRead> page = new Page<MeterHandRead>(pageNo, pageSize);
		List<MeterHandRead> pageList = meterHandReadService.queryAllRoomHandList(page, roomId);
        page.setRecords(pageList);
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}
	
	/**
	  *   添加
	 * @param meterHandRead
	 * @return
	 */
	@AutoLog(value = "手抄表-添加")
	@ApiOperation(value="手抄表-添加", notes="手抄表-添加")
	@PostMapping(value = "/add")
	public Result<MeterHandRead> add(@RequestBody MeterHandRead meterHandRead) {
		Result<MeterHandRead> result = new Result<MeterHandRead>();
		try {
			meterHandReadService.save(meterHandRead);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param meterHandRead
	 * @return
	 */
	@AutoLog(value = "手抄表-编辑")
	@ApiOperation(value="手抄表-编辑", notes="手抄表-编辑")
	@PutMapping(value = "/edit")
	public Result<MeterHandRead> edit(@RequestBody MeterHandRead meterHandRead) {
		Result<MeterHandRead> result = new Result<MeterHandRead>();
		MeterHandRead meterHandReadEntity = meterHandReadService.getById(meterHandRead.getId());
		if(meterHandReadEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = meterHandReadService.updateById(meterHandRead);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "手抄表-通过id删除")
	@ApiOperation(value="手抄表-通过id删除", notes="手抄表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			meterHandReadService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "手抄表-批量删除")
	@ApiOperation(value="手抄表-批量删除", notes="手抄表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<MeterHandRead> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<MeterHandRead> result = new Result<MeterHandRead>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.meterHandReadService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "手抄表-通过id查询")
	@ApiOperation(value="手抄表-通过id查询", notes="手抄表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MeterHandRead> queryById(@RequestParam(name="id",required=true) String id) {
		Result<MeterHandRead> result = new Result<MeterHandRead>();
		MeterHandRead meterHandRead = meterHandReadService.getById(id);
		if(meterHandRead==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(meterHandRead);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<MeterHandRead> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              MeterHandRead meterHandRead = JSON.parseObject(deString, MeterHandRead.class);
              queryWrapper = QueryGenerator.initQueryWrapper(meterHandRead, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<MeterHandRead> pageList = meterHandReadService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "手抄表列表");
      mv.addObject(NormalExcelConstants.CLASS, MeterHandRead.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("手抄表列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam("projectId")String projectId) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setNeedSave(true);
          int successNum = 0;
          int failureNum = 0;
          int row = 2;
          StringBuilder failureMsg = new StringBuilder();
          SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
          DateUtil dateUtil = DateUtil.builder().build();
          ArrayList<MeterHadnExVo> meterHandList = Lists.newArrayList();
          StringBuilder resueFailure = new StringBuilder();
          try {
              List<MeterHadnExVo> listMeterHandReads = ExcelImportUtil.importExcel(file.getInputStream(), MeterHadnExVo.class, params);
              if (null != listMeterHandReads ){
                  for (MeterHadnExVo meterHandRead:listMeterHandReads){
                      if (meterHandRead.getRoomName() == null){
                          return Result.error("该文件中存在房间数据为空");
                      }
                      String roomName = meterHandRead.getRoomName().trim();
                      if (roomName.contains(".0")){
                          roomName    = meterHandRead.getRoomName().trim().substring(0, meterHandRead.getRoomName().indexOf("."));
                          meterHandRead.setRoomName(roomName);
                      }
                  }
                  Map<MeterHadnExVo, List<MeterHadnExVo>> collect = listMeterHandReads.stream().collect(Collectors.groupingBy(Function.identity()));
                  for(Map.Entry<MeterHadnExVo, List<MeterHadnExVo>> entry : collect.entrySet()){
                      if(entry.getValue().size()>1){
                          List<MeterHadnExVo> reMeterHand = entry.getValue();
                          for (MeterHadnExVo mh:reMeterHand){
                              resueFailure.append(mh.getFloorName()+mh.getRoomName()+"|");
                          }
                          return   Result.error(resueFailure+"房间数据重复");
                      }
                  }
                  for (MeterHadnExVo vo:listMeterHandReads){
                      MeterHandRead meterHandRead = new MeterHandRead();
                      BeanUtils.copyProperties(vo,meterHandRead);
                      //查询选择的项目是否一致
                      if (StringUtils.isEmpty(meterHandRead.getProjectName().trim())){
                          failureMsg.append("<br/>第").append(row).append("行：请输入项目名称; ");
                          failureNum++;
                          row++;
                          continue;
                      }
                      //查询项目名字是否与ID一致
                      String projectName = meterService.queryProjectName(projectId);
                      if (projectName.equals(meterHandRead.getProjectName().trim())){
                          meterHandRead.setProjectName(meterHandRead.getProjectName());
                          meterHandRead.setProjectId(projectId);
                      }else {
                          failureMsg.append("<br/>第").append(row).append("行：请输入与选择项目一致的名称; ");
                          failureNum++;
                          row++;
                          continue;
                      }
                      if(StringUtils.isNotEmpty(meterHandRead.getFloorName())){
                          //查询楼宇ID 依据项目ID，楼宇名称
                          String floorId = meterService.queryFloorName(projectId, meterHandRead.getFloorName().trim());
                          if (StringUtils.isEmpty(floorId)){
                              failureMsg.append("<br/>第").append(row).append("行：请输入正确的楼宇名称; ");
                              failureNum++;
                              row++;
                              continue;
                          }
                          if (StringUtils.isNotEmpty(meterHandRead.getRoomName())){
                              String roomId = meterService.queryRoomName(floorId,meterHandRead.getRoomName());
                              if (StringUtils.isEmpty(roomId)){
                                  failureMsg.append("<br/>第").append(row).append("行：请输入正确的房间名称; ");
                                  failureNum++;
                                  row++;
                                  continue;
                              }
                              meterHandRead.setRoomId(roomId);
                          }else {
                              failureMsg.append("<br/>第").append(row).append("行：请输入房间名称; ");
                              failureNum++;
                              row++;
                              continue;
                          }
                      }else {
                          failureMsg.append("<br/>第").append(row).append("行：请输入楼宇名称; ");
                          failureNum++;
                          row++;
                          continue;
                      }
                      String feeCodeName = meterHandRead.getFeeCodeName().trim();
                      ChargeFeeitem chargeFeeitem = new ChargeFeeitem();
                      if (StringUtils.isNotEmpty(feeCodeName)){
                          List<ChargeFeeitem> chargeFeeitems = meterHandReadService.queryFeeItemByCode(null,feeCodeName);
                          if (chargeFeeitems.size() >1 ){
                              if (StringUtils.isEmpty(meterHandRead.getFeeCode().trim())){
                                  failureMsg.append("<br/>第").append(row).append("行：请输入收费项编号 ");
                                  failureNum++;
                                  row++;
                                  continue;
                              }
                              ChargeFeeitem  cfm = meterHandReadService.queryChargeFeeItemByCodeAndName(feeCodeName,meterHandRead.getFeeCode().trim());
                              if (null == cfm ){
                                  failureMsg.append("<br/>第").append(row).append("行：该收费项名名称,编号在系统不存在 ");
                                  failureNum++;
                                  row++;
                                  continue;
                              }
                              chargeFeeitem = cfm;
                          }else if (chargeFeeitems == null){
                              failureMsg.append("<br/>第").append(row).append("行：请输入正确的收费项名称 ");
                              failureNum++;
                              row++;
                              continue;
                          }else {
                              chargeFeeitem =chargeFeeitems.get(0);
                          }
                          meterHandRead.setFeeId(chargeFeeitem.getId());
                      }else {
                        failureMsg.append("<br/>第").append(row).append("行：请输入收费项名称 ");
                        failureNum++;
                        row++;
                        continue;
                    }
                    if (StringUtils.isEmpty(meterHandRead.getReadMonth())){
                        failureMsg.append("<br/>第").append(row).append("行：请输入计量月 ");
                        failureNum++;
                        row++;
                        continue;
                    }

                    if (StringUtils.isEmpty(meterHandRead.getNewRead())){
                        failureMsg.append("<br/>第").append(row).append("行：请输入本次读数 ");
                        failureNum++;
                        row++;
                        continue;
                    }
                    ChargeFeeRule chargeFeeRule =  meterHandReadService.queryChargeRule(meterHandRead.getFeeId(),meterHandRead.getRoomId());
                      if (null == chargeFeeRule){
                          failureMsg.append("<br/>第").append(row).append("行：该房间没有配置所填写收费项 ");
                          failureNum++;
                          row++;
                          continue;
                      }
                      MeterHandRead oldMhr = meterHandReadService.queryChargeLastRead(meterHandRead.getFeeId(),meterHandRead.getRoomId());
                      meterHandRead.setFeeId(chargeFeeitem.getId());
                      meterHandRead.setBillsStatus(0);
                      BigDecimal price =  chargeFeeRule.getPrice();
                      Integer unitAccount = chargeFeeRule.getUnitAccount();
                      if (null == unitAccount){
                          unitAccount = 2;
                      }
                      String readMonth = meterHandRead.getReadMonth().trim();
                      if (readMonth.length() == 6){
                          readMonth = readMonth.replace("-","-0");
                      }
                      BigDecimal nowRead = new BigDecimal(meterHandRead.getNewRead().trim());
                      meterHandRead.setPrice(price);
                      BigDecimal preRead = StringUtils.isNotBlank(meterHandRead.getPreRead())? new BigDecimal(meterHandRead.getPreRead()):BigDecimal.ZERO;
                      if (preRead.compareTo(nowRead) > 0){
                          failureMsg.append("<br/>第").append(row).append("行：期初数大于期末数！");
                          failureNum++;
                          row++;
                          continue;
                      }
                      if (null == oldMhr){
                          BigDecimal used = nowRead.subtract(preRead);
                          BigDecimal amount = used.multiply(price).setScale(unitAccount,BigDecimal.ROUND_HALF_UP);
                          meterHandRead.setAmount(amount);
                          meterHandRead.setUsed(used);
                          meterHandRead.setReadMonth(readMonth);
                          meterHandRead.setCoverStartDate(dateFormat.parse(dateUtil.getMinMonthDate(readMonth)));
                          meterHandRead.setCoverEndDate(dateFormat.parse(dateUtil.getMaxMonthDate(readMonth)));
                          meterHandRead.setCoverDate(readMonth+"~"+readMonth);
                      }else{
                          //第二次抄表 获取计量月是否小于抄表月
                          String oldReadMonth = oldMhr.getReadMonth();
                          if (StringUtils.isNotEmpty(meterHandRead.getPreRead())){
                              if (preRead.compareTo(new BigDecimal(oldMhr.getNewRead()))!=0){

                              }
                          }
                        int i = oldReadMonth.compareTo(readMonth);
                        if (i >= 0){
                              failureMsg.append("<br/>第").append(row).append("行：当前月份已经抄表 ");
                              failureNum++;
                              row++;
                              continue;
                          }
                          BigDecimal nowUsed = nowRead.subtract(new BigDecimal(oldMhr.getNewRead()));
                          meterHandRead.setUsed(nowUsed);
                          meterHandRead.setAmount(nowUsed.multiply(price).setScale(unitAccount,BigDecimal.ROUND_HALF_UP));
                          meterHandRead.setPreRead(oldMhr.getNewRead());
                          //计算是否是跨月账单
                          int count = dateUtil.compareToInt(oldReadMonth, readMonth);
                          if (count > 1){
                              //跨月账单 上次月份+1
                              String startMonth = dateUtil.addMonth(oldReadMonth);
                              String minMonthDate = dateUtil.getMinMonthDate(startMonth);
                              String endMonthDate = dateUtil.getMaxMonthDate(readMonth);
                              meterHandRead.setReadMonth(readMonth);
                              meterHandRead.setCoverStartDate(dateFormat.parse(minMonthDate));
                              meterHandRead.setCoverEndDate(dateFormat.parse(endMonthDate));
                              meterHandRead.setCoverDate(startMonth+"~"+readMonth);
                          }else {
                              meterHandRead.setReadMonth(readMonth);
                              meterHandRead.setCoverStartDate(dateFormat.parse(dateUtil.getMinMonthDate(readMonth)));
                              meterHandRead.setCoverEndDate(dateFormat.parse(dateUtil.getMaxMonthDate(readMonth)));
                              meterHandRead.setCoverDate(readMonth+"~"+readMonth);
                          }
                      }
                     // meterHandList.add(meterHandRead);
                      successNum++;
                      row++;
                      meterHandReadService.save(meterHandRead);
                  }
                  if (failureNum > 0 ){
                      return Result.error("文件导入失败！详细信息"+failureMsg);
                  }
                //  meterHandReadService.saveBatch(meterHandList);
                  return Result.ok("文件导入成功！数据行数:" + successNum+"条记录"+failureMsg);
              }
              return Result.error("导入电表基础信息失败！Excel数据为空");
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }
	 @RequestMapping("/queryFeeList")
	 public Result<List<ChargeFeeitem>> queryFeeList(){
		 List<ChargeFeeitem> chargeFeeitems = meterHandReadService.queryFeeList();
         return Result.ok(chargeFeeitems);
  }
  @RequestMapping("/queryProjectList")
     public  Result<List<BaseProject>> queryProjectList(@RequestParam("parentId")String parentId){
      Result<List<BaseProject>> result = new Result<>();
      List<BaseProject> projectList = meterHandReadService.queryProjectList(parentId);
      result.setSuccess(true);
      result.setResult(projectList);
      return  result;
  }
    @PostMapping ("readUseByHand")
	 public Result<?> readUseByHand(@RequestParam("roomId")String roomId,
		                            @RequestParam("nowUse")String nowUse,
									@RequestParam("readMonth")String readMonth,
									@RequestParam("feeId")String feeId) throws ParseException {
		Result<Object> result = new Result<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		DateUtil dateUtil = DateUtil.builder().build();
		//查询选择的收费项是否配置标准
        ChargeFeeRule chargeFeeRule =  meterHandReadService.queryChargeRule(feeId,roomId);
	    if (null == chargeFeeRule){
	  	return Result.error("该房间未配置该收费项");
	   }
	    if (StringUtils.isNotEmpty(readMonth)){
	    	readMonth = readMonth.trim();
		}
	    //查询最后一次抄表是否存在
		MeterHandRead meterHandRead = meterHandReadService.queryChargeLastRead(feeId,roomId);
	    MeterHandRead mhr = new MeterHandRead();
		mhr.setFeeId(feeId);
		mhr.setBillsStatus(0);
		//单价
        Integer unitAccount = chargeFeeRule.getUnitAccount();
        if(null == unitAccount){
            unitAccount = 2;
        }

        BigDecimal price =  chargeFeeRule.getPrice();
		BigDecimal nowRead = new BigDecimal(nowUse);
		mhr.setNewRead(nowUse);
		mhr.setPrice(price);
		mhr.setRoomId(roomId);
		mhr.setProjectId(chargeFeeRule.getProjectId());
	    if (null == meterHandRead){
			//第一次抄表 计算金额
			BigDecimal amount = nowRead.multiply(price).setScale(unitAccount,BigDecimal.ROUND_HALF_UP);
			mhr.setAmount(amount);
			mhr.setPreRead("0");
			mhr.setUsed(new BigDecimal(nowUse));
			mhr.setReadMonth(readMonth);
			mhr.setCoverStartDate(dateFormat.parse(dateUtil.getMinMonthDate(readMonth)));
			mhr.setCoverEndDate(dateFormat.parse(dateUtil.getMaxMonthDate(readMonth)));
			mhr.setCoverDate(readMonth+"~"+readMonth);
	    }else {
			//第二次抄表 获取计量月是否小于抄表月
            String newRead = meterHandRead.getNewRead();
            if (nowUse.compareTo(newRead) < 0){
                return Result.error("当前读数小于上一次读数");
            }
            String oldReadMonth = meterHandRead.getReadMonth();
			int i = oldReadMonth.compareTo(readMonth);
			if (i >= 0){
				return Result.error("当前月份已经抄表");
			}
			BigDecimal nowUsed = nowRead.subtract(new BigDecimal(newRead));
			mhr.setUsed(nowUsed);
			mhr.setAmount(nowUsed.multiply(price).setScale(unitAccount,BigDecimal.ROUND_HALF_UP));
			mhr.setPreRead(newRead);
			//计算是否是跨月账单
			int count = dateUtil.compareToInt(oldReadMonth, readMonth);
		    if (count > 1){
		    	//跨月账单 上次月份+1
				String startMonth = dateUtil.addMonth(oldReadMonth);
				String minMonthDate = dateUtil.getMinMonthDate(startMonth);
				String endMonthDate = dateUtil.getMaxMonthDate(readMonth);
				mhr.setReadMonth(readMonth);
				mhr.setCoverStartDate(dateFormat.parse(minMonthDate));
				mhr.setCoverEndDate(dateFormat.parse(endMonthDate));
				mhr.setCoverDate(startMonth+"~"+readMonth);
			}else {
		    	mhr.setReadMonth(readMonth);
				mhr.setCoverStartDate(dateFormat.parse(dateUtil.getMinMonthDate(readMonth)));
				mhr.setCoverEndDate(dateFormat.parse(dateUtil.getMaxMonthDate(readMonth)));
				mhr.setCoverDate(readMonth+"~"+readMonth);
			}
	    }
	    try {
			meterHandReadService.save(mhr);
			result.setSuccess(true);
			result.setMessage("抄表成功");
		}catch (Exception e){
			result.setSuccess(false);
			result.setMessage("抄表失败");
		}
	    return result;
  }
	/**
	 * 清除读数
	 */
    @RequestMapping("clearRead")
	public Result<?> clearRead(@RequestParam("id")String id){
		Result<Object> result = new Result<>();
        try {
            MeterHandRead meterHandRead = meterHandReadService.getById(id);

            if (null == meterHandRead){
                return Result.error("未找到对应的实体");
            }
            if (meterHandRead.getBillsStatus()==1){
                 return Result.error("账单已生成不可清除读数");	//账单已生成 不可清除
            }
             //获取最后一次抄表日期
            MeterHandRead lastRead = meterHandReadService.queryChargeLastRead(meterHandRead.getFeeId(),meterHandRead.getRoomId());
            if (!lastRead.getId().equals(id)){
                return Result.error("只可删除最后一次抄读数");
            }
			meterHandReadService.removeById(id);
			result.setMessage("清除成功");
			result.setSuccess(true);
		}catch (Exception e){
			result.setMessage("清除失败");
			result.setSuccess(false);
		}
		return result;
	}
	/**
	 * 生成手抄表账单 - 单个
	 */
     @RequestMapping("generateHandMeterBills")
     public Result<?> generateHandMeterBills(@RequestParam("id")String id){
		 Result<Object> result = new Result<>();
         try {
             MeterHandRead meterHand = meterHandReadService.getById(id);
             if (meterHand != null && meterHand.getBillsStatus() == 1){
                return Result.error("该账单已生成");
             }
             ChargeBills chargeBills = new ChargeBills();
             chargeBills.setProjectId(meterHand.getProjectId());
             BaseCustomer baseCustomer = meterHandReadService.queryCustomerInfo(meterHand.getRoomId());
             if (baseCustomer != null){
                 chargeBills.setCustomerId(baseCustomer.getId());
                 chargeBills.setFloorId(baseCustomer.getFloorId());
             }
             BaseTenant baseTenant =  meterHandReadService.queryTenantInfo(meterHand.getRoomId());
             if (baseTenant != null){
                 chargeBills.setRentId(baseTenant.getId());
                 chargeBills.setFloorId(baseTenant.getFloorId());
             }
             if (StringUtils.isBlank(chargeBills.getRentId())&&StringUtils.isBlank(chargeBills.getCustomerId())){
                 return Result.error("房间无业主或租户,账单生成失败！");
             }
             LoginUser user = SsoUtil.getLoginUser();
             chargeBills.setZjCny(meterHand.getReadMonth());
             chargeBills.setDue(meterHand.getAmount());
             chargeBills.setThisReading(Double.parseDouble(meterHand.getNewRead()));
             chargeBills.setLastReading(Double.parseDouble(meterHand.getPreRead()));
             chargeBills.setUnitPrice(meterHand.getPrice().doubleValue());
             chargeBills.setElapsedNum(meterHand.getUsed().doubleValue());
             chargeBills.setFeePrice(Double.valueOf(meterHand.getPrice().toString()));
             chargeBills.setFeeitemId(meterHand.getFeeId());
             chargeBills.setDateRange(meterHand.getCoverDate());
             chargeBills.setBillsExp(meterHand.getCoverDate());
             chargeBills.setTableId(meterHand.getId());
             chargeBills.setRoomId(meterHand.getRoomId());
             chargeBills.setCreateBy(user.getId());
             chargeBills.setCreateTime(new Date());
             chargeBills.setUpdateBy(user.getId());
             chargeBills.setUpdateTime(new Date());
             //查询收费
             ChargeFeeRule chargeFeeRule = meterHandReadService.queryChargeRule(meterHand.getFeeId(),meterHand.getRoomId());
             chargeBills.setFeeType(chargeFeeRule.getComputingType().toString());
             boolean res = feignChargeService.saveChargeBills(chargeBills,user.getTenantId());
             if ( res ){
                 meterHandReadService.updateBillsStatus(id);
                 return Result.ok("生成账单成功");
             }
             return Result.error("生成账单失败!");
		 }catch (Exception e){
			 result.setSuccess(false);
			 result.setMessage("系统繁忙,生成账单失败!");
			 log.error("手抄表生成账单失败",e);
		 }
		 return result;
	 }

    /**
     * 批量生成账单
     */
    @RequestMapping("generaBillBatch")
    public Result<?> generaBillBatch(@RequestParam("id")String ids){
        Result<Object> result = new Result<>();
        if (StringUtils.isEmpty(ids)){
            return Result.error("请选择需要生成的账单");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        try {
            String s = meterHandReadService.saveBatchBills(idList);
            result.setMessage(s);
            result.setSuccess(true);
        }catch (Exception e){
            log.info(e.getMessage());
        }
        return result;
    }



    /**
     * handReadList
     *
     */
    @RequestMapping("handHistoryRead")
    public Result<?> handHistoryRead(@RequestParam("id")String id, @Param("feeId")String feeId){
        Result<Object> result = new Result<>();
        List<MeterHandRead> meterHandReads = meterHandReadService.handHistoryRead(id,feeId);
        result.setSuccess(true);
        result.setResult(meterHandReads);
        return  result;
    }
    /**
     * 查询手抄列表
     */
    @RequestMapping("allRead")
    public   Result<IPage<MeterHandRead >>  allRead(BaseRoomMeterVo baseRoomMeterVo,
                                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
        Result<IPage<MeterHandRead>> result = new Result<IPage<MeterHandRead>>();
        Page<MeterHandRead> page = new Page<MeterHandRead>(pageNo, pageSize);
        List<MeterHandRead> meterHandReadList =meterHandReadService.allRead(page,baseRoomMeterVo);
        page.setRecords(meterHandReadList);
        result.setSuccess(true);
        result.setResult(page);
        return result;
    }

}
